<script setup lang="ts">
import { onLoa0d, onReachBottom, onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";
import { certificationAdd } from "@/apis/collectionCertification";
import {
  apiProductAuth,
  apiProductAuthCost,
  apiProductDetails,
} from "@/apis/product";
import { onShow } from "@dcloudio/uni-app";
import { uniChooseImg, uniChooseMedia } from "@/utils/uniToos";
import { uploadImg } from "@/utils/request";
import { toast } from "@/utils/tools";
import { apiComfirmOrder, wxPayMiniAppPay } from "@/apis/order";
const productId = ref(0);
const productDetail = ref({});
const iamgeListArr = ref([]);
const videoListArr = ref([]);
const authCost = ref(0);
const chooseUploadRef = ref(false);
const data = reactive({
  formData: {
    shopGoodsId: "",
    images: [],
    videos: [],
    otherImages: [],
    money: "1",
  },
  rules: {},
});
const imgList = ref([]);
let columns = ref([["中国", "美国", "日本"]]);
let typePickerOpen = ref(); //类型弹窗

const isImg = (url = "") => {
  if (
    url.indexOf(".png") > -1 ||
    url.indexOf(".jpg") > -1 ||
    url.indexOf(".jpeg") > -1 ||
    url.indexOf(".webp") > -1
  ) {
    return true;
  }
  return false;
};

const uploadImages = async () => {
  let filePath = await uniChooseImg();
  let res = await uploadImg(filePath);
  data.formData.images.push(res.data.url);
  // const files = (await uniChooseMedia({ mediaType: ["image"] })) as any[];
  // let res = await uploadImg(files.join(","));
  // data.formData.images.push(...res.data.url.split(","));
};
// 上传其他认证证书
const uploadOtherImg = async () => {
  let filePath = await uniChooseImg();
  let res = await uploadImg(filePath);
  data.formData.otherImages.push(res.data.url);
};
// 类型弹窗确认
const typeconfirm = (e: any) => {
};
// 类型选择弹窗
const typeClick = () => {
  typePickerOpen.value.open();
};
const getProductDetail = async () => {
  let res = await apiProductDetails({
    id: data.formData.shopGoodsId,
  });
  // Object.assign(data.formData, res.data);
  // data.formData.types = res.data.types;
  // data.formData.brand = res.data.brand;
  // data.formData.fineness = res.data.fineness;
  data.formData.dict = JSON.parse(res.data.dict);

  data.formData.describes = res.data.describes;
};

const appCommodityId = ref([]);
const goodsWaterfallMyRef = ref();
const shoppingId = ref();
const num = ref();
const price = ref();
const comfirmOrder = async () => {
  let params = {
    commodityId: appCommodityId.value, //商品ID
    commodityName: null, //商品的标题名称
    actualPayment: authCost.value, //支付价格
    userAddressId: null, //发货地址ID
    type: 3, //消费类型  0-开会员  1-开商铺  2-购买商品  3-藏品认证  4-评价费用
    activitiesId: null, //评选活动Id
    appCommodityList: null, // 4评价活动的时候传
    collectionCertificationList: data.formData, // 3藏品认证的时候传
  };
  // let res = await apiComfirmOrder(params);
  // if (res.code == 200) {
  //   shoppingId.value = res.data.shopingId;
  //   num.value = res.data.num;
  //   price.value = res.data.price;
  //   wxPayMiniAppPayFn();
  // }
  await wxPayMiniAppPayFn(params);
};
const wxPayMiniAppPayFn = async (params:any) => {
  let res = await wxPayMiniAppPay(params);
  if (res.code == 200) {
    let dataObj = res.data;
    wx.openEmbeddedMiniProgram({
      appId: dataObj.appId,
      path: dataObj.path,
      envVersion: 'release',//正常跳转路径
      success(res) {
        uni.setStorageSync('isPaySuccess',true)
      }
    })
  }
};
const handleSubmitAuth = async () => {
  let images: any[] = [];
  let otherImagesArr: any[] = [];
  for (const key in iamgeListArr.value) {
    images.push(iamgeListArr.value[key]["url"]);
  }
  for (const key in videoListArr.value) {
    otherImagesArr.push(videoListArr.value[key]["url"]);
  }
  // data.formData.images = images.join(",");
  // data.formData.otherImages = otherImagesArr.join(",");
  data.formData.images = iamgeListArr.value.join(",");
  data.formData.otherImages = videoListArr.value.join(",");
  comfirmOrder();
};

// 获取认证费用
const getProductAuthCost = async () => {
  let res = await apiProductAuthCost({});
  if (res.data.member) {
    authCost.value = res.data.member;
  }
};

const getLimit = () => {
  if (isImg(iamgeListArr?.value?.[0])) {
    return 9;
  }

  return 1;
};

const handleChooseUpload = () => {
  if (isImg(iamgeListArr?.value?.[0])) {
    handleUploadImage();
    return;
  }
  chooseUploadRef.value = true;
};

const handleUploadImage = () => {
  uni.chooseImage({
    count: 9,
    sizeType: ["original", "compressed"],
    sourceType: ["album"],
    success: (imgRes: any) => {
      uni.showLoading({ title: "上传中..." });
      let files = imgRes.tempFiles;
      files.forEach(async (item: any, index: number) => {
        let res = await uploadImg(item.path);
        // data.formData.images.push(res.data.url);
        iamgeListArr.value.push(res.data.url);
      });
      uni.hideLoading();
    },
  });
};

const handleUploadVideo = async () => {
  uni.chooseVideo({
    sourceType: ["camera", "album"],
    compressed: true, // 需要压缩
    maxDuration: 60,
    success: async function (res) {
      uni.showLoading({ title: "上传中..." });
      if (res.size > 1024 * 1024 * 10) {
        toast("视频过大请重新上传！");
      }
      let resVideoUpload = await uploadImg(res.tempFilePath);
      let imagesArr = [];
      imagesArr.push(resVideoUpload.data.url);
      iamgeListArr.value.push(resVideoUpload.data.url);
      // data.formData.images = imagesArr.join(",");
      data.formData.images.push(resVideoUpload.data.url);
      uni.hideLoading();
    },
  });
};

const handleOtherUploadImage = () => {
  uni.chooseImage({
    count: 9,
    sizeType: ["original", "compressed"],
    sourceType: ["album"],
    success: (imgRes: any) => {
      uni.showLoading({ title: "上传中..." });
      let files = imgRes.tempFiles;
      files.forEach(async (item: any, index: number) => {
        let res = await uploadImg(item.path);
        // data.formData.otherImages = imagesArr.join(",");
        // data.formData.otherImages.push(res.data.url);
        videoListArr.value.push(res.data.url);
      });
      uni.hideLoading();
    },
  });
};

const handleClose = (index: number = 0) => {
  iamgeListArr.value.splice(index, 1);
};

const handleClose1 = (index: number = 0) => {
  videoListArr.value.splice(index, 1);
};

onShow(() => {
  getProductDetail();
  getProductAuthCost();
});
onLoad((options: any) => {
  appCommodityId.value = options.productId;
  data.formData.shopGoodsId = options.productId;
});
</script>

<template>
  <view class="body-box">
    <view class="row-box info-box mar-box">
      <view class="title-box">添加藏品描述信息~</view>
      <textarea
        maxlength="-1"
        v-model="data.formData.describes"
        placeholder="请详细描述奇石信息~"
      ></textarea>
    </view>
    <view class="row-box">
      <view class="menu-box" v-for="item in data.formData.dict">
        <!-- {{  }} -->
        <view class="crosswise">
          <view class="li-title">藏品{{ item.fieldName }}：</view>
          <view class="select-box" @tap="typeClick">
            <!-- <text>请选择</text> -->
            <text>{{ item.name }}</text>
            <!-- <uv-picker ref="typePickerOpen" :columns="columns" @confirm="typeconfirm"></uv-picker> -->
          </view>
        </view>
      </view>
    </view>
    <view class="form-upload-card form-input-bg row-box">
      <view class="title-box"> 添加藏品视频或图片~ </view>
      <!-- <uv-line color="#000000" ></uv-line> -->
      <!-- <view class="line"></view> -->
      <!-- <uv-line length="100%" color="#CECECE"></uv-line> -->

      <view class="form-upload">
        <view class="form-upload-img">
          <view
            v-for="(item, index) in iamgeListArr"
            :key="index"
            class="image"
          >
            <image v-if="isImg(item)" :src="item" mode="scaleToFill" />
            <video class="image" v-else :src="item" />
            <view class="close flex flex-center" @click="handleClose(index)">
              <view class="close-line"></view>
            </view>
          </view>
          <view
            class="upload-btn-bg image"
            @click="handleChooseUpload"
            v-if="iamgeListArr.length < getLimit()"
          >
            <image
              class="icon-plus"
              src="@/static/images/plus.png"
              mode="scaleToFill"
            />
            <text class="upload-btn-text">添加图片</text>
          </view>
        </view>
        <!-- <uv-upload :fileList="imgList" name="1" multiple :maxCount="3" @afterRead="handleUploadImage"
                        uploadText="点击上传" @delete=""></uv-upload> -->
      </view>
    </view>
    <view class="form-upload-card form-input-bg row-box">
      <view class="title-box"> 添加藏品其他认证证书~ </view>
      <!-- <uv-line color="#000000" ></uv-line> -->
      <!-- <view class="line"></view> -->
      <!-- <uv-line length="100%" color="#CECECE"></uv-line> -->

      <view class="form-upload">
        <view class="form-upload-img">
          <!-- <image
            class="image"
            v-for="(item, index) in videoListArr"
            :src="item"
            :key="index"
            mode="scaleToFill"
          /> -->
          <view
            v-for="(item, index) in videoListArr"
            :key="index"
            class="image"
          >
            <image :src="item" mode="scaleToFill" />
            <view class="close flex flex-center" @click="handleClose1(index)">
              <view class="close-line"></view>
            </view>
          </view>
          <view
            class="upload-btn-bg image"
            @click="handleOtherUploadImage"
            v-if="imgList.length < 9"
          >
            <image
              class="icon-plus"
              src="@/static/images/plus.png"
              mode="scaleToFill"
            />
            <text class="upload-btn-text">添加图片</text>
          </view>
        </view>
        <!-- <uv-upload :fileList="imgList" name="1" multiple :maxCount="3" @afterRead="handleUploadImage"
                        uploadText="点击上传" @delete=""></uv-upload> -->
      </view>
    </view>
    <view class="row-box cost-box crosswise-sp">
      <!-- <view>认证费用：{{ authCost }}（系统自动带出）</view> -->
      <view>认证费用：{{ authCost }}</view>
      <view class="unit">元</view>
    </view>
    <view class="pay-box">
      <button @click="handleSubmitAuth">缴费并认证</button>
    </view>
  </view>

  <uv-overlay :show="chooseUploadRef" @click="chooseUploadRef = false">
    <view class="choose flex flex-column flex-center">
      <view @click="handleUploadImage">选择图片</view>
      <view class="line">
        <uv-line></uv-line>
      </view>
      <view @click="handleUploadVideo">选择视频</view>
    </view>
  </uv-overlay>
</template>

<style lang="scss" scoped>
//
.body-box {
  padding: 0 30rpx 200rpx;
}

.row-box {
  margin-bottom: 24rpx;
}

.mar-box {
  margin-top: 24rpx;
}

.title-box {
  padding: 0 0 30rpx;
  color: rgba(51, 51, 51, 1);
  font-size: 28rpx;
  border-bottom: 2rpx solid rgba(206, 206, 206, 1);
}

.info-box {
  margin-bottom: 24rpx;

  textarea {
    width: 100%;
    height: 240rpx;
    margin-top: 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
  }
}

.form-upload-card {
  height: 100%;
  margin-bottom: 30rpx;

  .form-upload-item {
    padding: 20rpx;
  }

  .form-upload {
    // padding: 20rpx;
    display: flex;
    height: 100%;

    .form-upload-img {
      // width: 100%;
      flex-wrap: wrap;
      // width: 100%;
      height: 100%;
      display: flex;
      // grid-template-columns: 33% 33% 33%; // justify-content: space-evenly;
      // grid-template-rows: 58%; // justify-content: space-evenly;
      // align-items: center;
    }

    .image {
      // flex-grow: 1;
      // justify-content: space-around;
      width: 144rpx;
      height: 144rpx;
      margin-right: 30rpx;
      margin-top: 30rpx;
      position: relative;

      .icon-plus {
        width: 48rpx;
        height: 48rpx;
      }

      .close {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
        background-color: #f3604e;
        width: 18px;
        height: 18px;
        border-radius: 50%;

        .close-line {
          background-color: #ffffff;
          height: 2px;
          width: 12px;
          border-radius: 1px;
        }
      }
    }

    .upload-btn-bg {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: #efefef;
    }

    .upload-btn-text {
      color: #cecece;
      font-size: 24rpx;
    }
  }
}

.menu-box {
  padding: 30rpx 0;
  color: rgba(51, 51, 51, 1);
  font-size: 28rpx;
  border-bottom: 2rpx solid rgba(239, 239, 239, 1);

  &:first-child {
    padding-top: 0;
  }

  &:last-child {
    padding-bottom: 0;
    border: none;
  }

  .select-box {
    color: rgba(136, 136, 136, 1);
  }
}

.cost-box {
  color: rgba(51, 51, 51, 1);
  font-size: 28rpx;

  .unit {
    color: rgba(154, 154, 154, 1);
    font-size: 28rpx;
  }
}

.pay-box {
  position: fixed;
  bottom: 60rpx;
  left: 0;
  width: 100%;
  padding: 0 60rpx;
  box-sizing: border-box;

  button {
    width: 100%;
    height: 100rpx;
    border-radius: 24rpx;
    background: linear-gradient(
      0deg,
      rgba(191, 1, 3, 1) 0%,
      rgba(255, 84, 2, 1) 99.2%
    );
    color: rgba(255, 255, 255, 1);
    font-size: 28rpx;
    border: 0rpx solid rgba(187, 187, 187, 1);
  }
}

.choose {
  border-radius: 10px 10px 0 0;
  position: absolute;
  bottom: 0;
  // right: 0;

  width: 100%;
  background-color: #ffffff;
  height: 150rpx;

  .line {
    margin: 10rpx 0;
    width: 100%;
  }
}
</style>
